from openai import OpenAI

class ChatBot:

    def __init__(self):
        self.flag=0
        self.cnt=0
        # 这个是预测心理健康的历史记录
        self.chat_history = []
        # 这个是与gpt聊天的历史记录
        self.chat_history2=[]
        self.userChoice=[]
        self.client = self.initialize_openai_client()
    def initialize_openai_client(self):
        return OpenAI(
            api_key="sk-LLiApxjE2gJ9juWeE4T6eAt8MFJHtxHSDSbH4LjNTAiFMH2u",
            base_url="https://api.chatanywhere.tech/v1"
        )

    def ask_openai_question(self, messages):
        response = self.client.chat.completions.create(model="gpt-3.5-turbo", messages=messages)
        return response.choices[0].message.content

    def interact_with_openai(self, user_input,type):
        # type=1即为心理健康测试2则为聊天测试接口
        # print(self.chat_history)
        if type==1:
            self.chat_history.append({'role': 'user', 'content': user_input})
            response = self.ask_openai_question(self.chat_history)
            # print("AI回复:", response)
            self.chat_history.append({'role': 'assistant', 'content': response})
            # 减少聊天记录，避免出现过大的聊天记录
            if len(self.chat_history) > 4:
                self.chat_history = self.chat_history[-4:]
            return response
        else:
            self.chat_history2.append({'role': 'user', 'content': user_input})
            response = self.ask_openai_question(self.chat_history2)
            # print("AI回复:", response)
            self.chat_history2.append({'role': 'assistant', 'content': response})
            # 减少聊天记录，避免出现过大的聊天记录
            if len(self.chat_history2) > 4:
                self.chat_history2 = self.chat_history2[-4:]
            return response

if __name__ == '__main__':
    chatbot = ChatBot()

    while True:
        user_input = input("请输入问题（或者直接回车退出）: ")
        if user_input.strip() == "":
            break
        response = chatbot.interact_with_openai(user_input)
        print(response)